<?php
/**
 * Class RedLuckPrivate
 * 手气红包算法
 */
namespace Pri\red;
defined('IN_IA') or exit('Access Denied');
class RedLuckPrivate
{
    /**
     * 分批红包
     * @param $_money
     * @param $_number
     * @return array
     */
    public function batch($_money,$_number)
    {
        $_num = $_number / 20;
        $_create_count = ceil($_num);
        $_last_count = 0;
        if($_create_count > $_num){
            $_last_count = $_number - (($_create_count-1) * 20);
        }else{
            $_create_count = $_num;
        }
        $_count_money = sprintf('%.2f',$_money / $_create_count);
        $_total_money =$_count_money * $_create_count;
        $_diff = sprintf('%.2f',$_money - $_total_money);
        $_last_money = $_count_money;
        if($_diff != 0){
            $_last_money += $_diff;
        }
        return array(
            "create_count"=>$_create_count,
            "last_count"=>$_last_count,
            "money"=>$_count_money,
            "last_money"=>$_last_money
        );
    }

    /**
     * 生成红包
     * @param $_money
     * @param $_number
     * @param int $_count
     * @param array $_data
     * @return array
     */
    public function redPicket($_money,$_number,$_count=1,$_data = array()){
        $_average = $_money/$_number;
        for($i=0;$i<$_number;$i++){
            $_num = $this->iRand(0.01,$_average);
            if($_count === 1){
                $_data[$i] = $_num;
            }else{
                $_data[$i] = sprintf('%.2f',$_data[$i]+$_num);
            }
            $_money = $_money-$_num;
        }
        if($_money/$_number > 0.01){
            return $this->redPicket($_money,$_number,++$_count,$_data);
        }else{
            $_max_index = mt_rand(0,count($_data)-1);
            $_data[$_max_index] = sprintf('%.2f',$_data[$_max_index]+$_money);
        }
        return $_data;
    }

    /**
     * 随机金额
     * @param $_min
     * @param $_max
     * @return string
     */
    private function iRand($_min,$_max){
        $_num = $_min + mt_rand() / mt_getrandmax() * ($_max - $_min);
        return sprintf("%.2f",$_num);
    }
}